import { message } from 'ant-design-vue';
import api from "@/utils/api";
import type {CtrlPlan, FailMode, Frequency, ReactionPlan} from "./type.ts";
import {computed, ref} from "vue";


export const fetching = ref(false);
export const cpList = ref<CtrlPlan[]>([]);
export const cpSearchList = ref<CtrlPlan[]>([]);
export const newCpName = ref();

// cp搜索方法
export const onCpSearch = async (spec: string, failModeId?: number) => {
    if((cpList.value===undefined || cpList.value.length===0) && failModeId){
        await fetchCtrlPlans(failModeId);
    }
    if(cpList.value){
        cpSearchList.value = cpList.value
            .filter(cp => cp.spec.includes(spec))
            .sort((a, b) => a.id - b.id);
    }
    if(spec.length>0){
        newCpName.value = spec;
    }
};

// 获取cp列表
export const fetchCtrlPlans = async (failModeId: number) => {
    try {
        fetching.value = true;

        const response = await api.get('/ctrlPlan', {
            params: {
                failModeId: failModeId,
            }
        });

        cpList.value = response.data;
    } catch (error) {
        message.error('获取控制计划列表失败');
        console.error('获取控制计划列表失败:', error);
    } finally {
        fetching.value = false;
    }
};

// 控制计划选择变化
export const onCpChange = (value: any,ctrlPlan:CtrlPlan) => {
    const cp= cpList.value.find(cp =>
        cp.spec === value
    );

    if (cp) {
        ctrlPlan.id=cp.id;
        ctrlPlan.spec=cp.spec;
        newCpName.value=undefined;
    }

};

export const isCpNew = computed(() => {
    return (newCpName && newCpName.value!==undefined)
})

// 控制计划失焦事件
export const onCpBlur = (ctrlPlan:CtrlPlan) => {
    if (isCpNew.value) {
        ctrlPlan.id=undefined;
        ctrlPlan.spec=newCpName.value;
        newCpName.value=undefined;
    }
};

export const createNewCtrlPlan = async (failModeId: number, spec: string,capacityId:number,requirementId:any) => {
    try {
        fetching.value = true;

        await api.post('/ctrlPlan', {
            failModeId: failModeId,
            spec: spec,
            capacityId: capacityId,
        });
        const response = await api.get('/ctrlPlan', {
            params: {
                failModeId: failModeId,
                spec: spec,
                capacityId: capacityId,
            }
        });
        if(response.data[0].id){
            await api.post('/ctrlPlan/bindRequirement', {
                requirementId: requirementId,
                ctrlPlanId: response.data[0].id,
            });
        }


        message.success(`新控制计划【${spec}】创建成功`);
        return true;
    } catch (error) {
        message.error('创建控制计划失败');
        console.error('创建控制计划失败:', error);
        return false;
    } finally {
        fetching.value = false;
    }
};

// 添加控制计划
export const addCtrlPlan = (failModes: FailMode[], failModeIndex: number) => {
    if (failModeIndex === undefined || failModeIndex < 0) {
        message.warning('请先选择一个痛点');
        return;
    }
    const failMode = failModes[failModeIndex];
    if (failMode) {
        const lastCtrlPlan = failMode.ctrlPlans[failMode.ctrlPlans.length - 1];
        if (lastCtrlPlan && lastCtrlPlan.spec?.trim() !== '') {
            failMode.ctrlPlans.push({
                id: undefined,
                spec: '',
                capacityId: 2,
                capacityCn: '一次',
                frequencies: [],
                reactionPlans: [],
            });
        } else {
            message.warning('请先填写当前控制计划');
        }
    }
};

// 移除控制计划
export const removeCtrlPlan = (failModes: FailMode[], failModeIndex: number, ctrlIndex: number) => {
    const failMode = failModes[failModeIndex];
    if (failMode && failMode.ctrlPlans.length > 1) {
        failMode.ctrlPlans.splice(ctrlIndex, 1);
    } else {
        message.warning('至少需要保留一个控制计划');
    }
};

// 关联频率
export const bindFrequencies = async (ctrlPlanId: number, frequencies: Frequency[], frequencyList: any[]) => {
    for (const frequencyCn of frequencies.map(f => f.cnDesc)) {
        const frequency = frequencyList.find(f => f.cnDesc === frequencyCn);
        if (frequency) {
            const frequencyBindData = {
                ctrlPlanId: ctrlPlanId,
                frequencyId: frequency.id
            };
            await api.post('/cpFrequency/bindCtrlPlan', frequencyBindData);
        }
    }
};

// 关联反应计划
export const bindReactionPlans = async (ctrlPlanId: number, reactionPlans: ReactionPlan[], reactionPlanList: any[]) => {
    for (const reactionPlanCn of reactionPlans.map(r => r.cnDesc)) {
        const reactionPlan = reactionPlanList.find(r => r.cnDesc === reactionPlanCn);
        if (reactionPlan) {
            const reactionPlanBindData = {
                ctrlPlanId: ctrlPlanId,
                reactionPlanId: reactionPlan.id
            };
            await api.post('/reactionPlan/bindCtrlPlan', reactionPlanBindData);
        }
    }
};

// 导出所有方法
export default {
    fetching,
    cpSearchList,
    cpList,
    onCpSearch,
    onCpChange,
    onCpBlur,
    createNewCtrlPlan,
    addCtrlPlan,
    removeCtrlPlan,
    bindFrequencies,
    bindReactionPlans,
};